#include <A_Config.h>
#include <USB.h>
#include <USBCDC.h>
#include "USBMSC.h"
USBMSC MSC;

static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize)
{
    size_t total_blk = bufsize / 512;
    for (size_t i = 0; i < total_blk; ++i)
    {
        SDCARD.writeRAW((uint8_t *)buffer + i * 512, lba + i);
    }
    return bufsize;
}

static int32_t onRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize)
{
    size_t total_blk = bufsize / 512;
    for (size_t i = 0; i < total_blk; ++i)
    {
        SDCARD.readRAW((uint8_t *)buffer + i * 512, lba + i);
    }
    return bufsize;
}

static void usbEventCallback(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    if (event_base == ARDUINO_USB_EVENTS)
    {
        arduino_usb_event_data_t *data = (arduino_usb_event_data_t *)event_data;
        switch (event_id)
        {
        case ARDUINO_USB_STARTED_EVENT:
            hal.USBConnected = true;
            break;
        case ARDUINO_USB_STOPPED_EVENT:
            hal.USBConnected = false;
            break;
        default:
            break;
        }
    }
}
void ClockHAL::setMediaPresent(bool isPresent)
{
    if (isPresent)
    {
        MSC.mediaPresent(true);
        MSC.begin(SDCARD.cardSize(), 512);
    }
    else
    {
        MSC.mediaPresent(false);
    }
}
void ClockHAL::setupMSC(void)
{
    USB.onEvent(usbEventCallback);
    MSC.onRead(onRead);
    MSC.onWrite(onWrite);
    MSC.mediaPresent(true);
    MSC.begin(SDCARD.cardSize() / 512, 512);
    USB.begin();
}
